import sys

#a method
def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.
    Returns string."""
    return ";".join(["%s=%s" % (k,v) for k,v in params.items() ])

# a method
def fib(n):
    print('n=',n)
    if(n>1):
        return n*fib(n-1)
    else:
        print('end of the line')
        return 1

#a method
def readFile(name):
    try:
        fsock = open("/notthere")
    except IOError:
        print ("The file does not exist, exiting gracefully")
    print("This line will always print")
    
# read file with MODE
def testMode(filePath):
    f = open(filePath, "rb") #以二进制方式打开文件
    print(f.mode) #
    print(f.name)    
    print(f.tell()) #被打开文件中当前位置
    print(f.seek(-128,2)) #移动到另一个位置
    print(f.tell())
    tagData = f.read(128) #从被打开文件中读取指定个数的字节，并且返回含有读取数据的字符串
    print("tagData=",tagData)
    print(f.tell())
    print(f.closed)
    f.close()
    print(f.closed)

# read file try and catch
def tryAndCatch(filename):
    try:
        fsock = open(filename, "rb", 0)
        try:
            fsock.seek(-128,2)
            tagdata = fsock.read(128)
        finally:
            fsock.close()
    except IOError:
        pass        

# write into file
def writeAFile():
    logfile = open("test.log", "w")
    logfile.write('test succeeded')
    logfile.close()
    print(open('test.log').read())
    logfile = open('test.log','a')
    logfile.write('line 2')
    logfile.close()
    print(open('test.log').read())

# test clauses.
print(sys.path)
print('Outing...')    
print(fib(5))
print(buildConnectionString.__name__)
print(fib.__name__)
readFile("abc")
testMode("D:\\aa.csv")
testMode("F:\\KuGou\\Black Eyed Peas - Boom Boom Pow.mp3")
writeAFile()


'''
Second Paragraph exercise
'''
def circleTest():
    li = ['a','b','c']
    for s in li:
        print(s)
    print("\n".join(li))
    
    # for counting
    for i in range(5):
        print(i)
    li = ['a','b','c','d','e']
    for i in range(len(li)):
        print(li[i])    

circleTest() ##

# circle test 2
import os
def dictTest():
    print('############ dictTest def begin... ###################')
    for k,v in os.environ.items():
        print("%s=%s" % (k,v))
    print('############ dictTest def done. ###################')
    print("\n".join(["%s=%s" % (k,v) for k,v in os.environ.items()])) ##快速显示集合列表项
        
dictTest() ## calling

# 全局模块
import sys
def getModules():
    print('######## getModules #############')
    print("\n".join(sys.modules.keys()))
    #print(sys.modules["fileinfo"])
      
getModules()        

# 目录操作
def dirOperations():
    print("######### dirOperations ##########")
    thePath = "F:\\TEMP\\2195248"
    print("\n".join(k for k in os.listdir(thePath)))
    print("--- folder & files --")
    for f in os.listdir(thePath):
        if os.path.isfile(os.path.join(thePath, f)):
            print("%s is real file." % f)
        if os.path.isdir(os.path.join(thePath, f)):
            print("%s is a folder." % f)    
    print("current pwd = ", os.getcwd())        
    
dirOperations()    

##
def listDirectory(directory, fileExtList):
    "get list of file info objects for files of particular extensions "
    fileList=[os.path.normpath(f) 
              for f in os.listdir(directory)]
    fileList=[os.path.join(directory,f)
              for f in fileList
              if os.path.splitext(f) in fileExtList]
    